import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Grid,
  Alert,
} from '@mui/material';
import axios from 'axios';
import { API_BASE_URL } from '../config';
function Transactions() {
  const [formData, setFormData] = useState({
    sender: '',
    recipient: '',
    amount: '',
  });
  const [status, setStatus] = useState({ type: '', message: '' });
  const [wallets, setWallets] = useState({});
  const [loading, setLoading] = useState(true);
  const [miner, setMiner] = useState('');
  const [mineStatus, setMineStatus] = useState({ type: '', message: '' });

  useEffect(() => {
    fetchWallets();
  }, []);

  const fetchWallets = async () => {
    try {
      const response = await axios.get(`${API_BASE_URL}/wallets`);
      setWallets(response.data); // { address1: balance1, ... }
      setLoading(false);
    } catch (err) {
      setStatus({ type: 'error', message: '获取钱包信息失败：' + (err.response?.data || err.message) });
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus({ type: '', message: '' });
    // 校验用户是否存在
    if (!wallets[formData.sender]) {
      setStatus({ type: 'error', message: '发送方用户不存在' });
      return;
    }
    if (!wallets[formData.recipient]) {
      setStatus({ type: 'error', message: '接收方用户不存在' });
      return;
    }
    // 校验余额
    if (parseInt(formData.amount) > wallets[formData.sender]) {
      setStatus({ type: 'error', message: '发送方余额不足' });
      return;
    }
    try {
      const response = await axios.post(`${API_BASE_URL}/transactions/new`, {
        sender: formData.sender,
        recipient: formData.recipient,
        amount: parseInt(formData.amount),
      });
      if (response.status === 200) {
        setStatus({
          type: 'success',
          message: '交易已成功提交！',
        });
        setFormData({ sender: '', recipient: '', amount: '' });
        fetchWallets(); // 刷新钱包信息
      } else {
        setStatus({
          type: 'error',
          message: '交易提交失败：服务器返回错误',
        });
      }
    } catch (error) {
      setStatus({
        type: 'error',
        message: error.response?.data || '交易提交失败：请检查网络连接',
      });
    }
  };

  const handleMine = async () => {
    setMineStatus({ type: '', message: '' });
    if (!miner) {
      setMineStatus({ type: 'error', message: '请输入矿工用户名' });
      return;
    }
    if (!wallets[miner]) {
      setMineStatus({ type: 'error', message: '矿工用户不存在' });
      return;
    }
    try {
      const response = await axios.get(`${API_BASE_URL}/mine/${miner}`);
      setMineStatus({ type: 'success', message: '挖矿成功！区块已添加。' });
      fetchWallets(); // 刷新钱包信息
    } catch (error) {
      setMineStatus({ type: 'error', message: error.response?.data || '挖矿失败' });
    }
  };

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="60vh">
        <Typography>正在加载钱包信息...</Typography>
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        创建新交易
      </Typography>

      {status.message && (
        <Alert severity={status.type} sx={{ mb: 2 }}>
          {status.message}
        </Alert>
      )}

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="发送方"
                  name="sender"
                  value={formData.sender}
                  onChange={handleChange}
                  required
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="接收方"
                  name="recipient"
                  value={formData.recipient}
                  onChange={handleChange}
                  required
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="金额"
                  name="amount"
                  type="number"
                  value={formData.amount}
                  onChange={handleChange}
                  required
                />
              </Grid>
              <Grid item xs={12}>
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  fullWidth
                >
                  提交交易
                </Button>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>

      <Card sx={{ mt: 4 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            挖矿
          </Typography>
          {mineStatus.message && (
            <Alert severity={mineStatus.type} sx={{ mb: 2 }}>{mineStatus.message}</Alert>
          )}
          <Box display="flex" gap={2} alignItems="center">
            <TextField
              label="矿工用户名"
              value={miner}
              onChange={e => setMiner(e.target.value)}
              placeholder="请输入矿工用户名"
            />
            <Button variant="contained" color="secondary" onClick={handleMine}>
              挖矿
            </Button>
          </Box>
        </CardContent>
      </Card>
    </Box>
  );
}

export default Transactions; 